<template>
  <div class="component-sku-stock-flow mod-stock-flow">
    <div class="search-bar">
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"

        @submit.prevent
      >
        <div class="input-row">
          <el-form-item :label="$t('takeStock.productFilter')+':'">
            <el-select
              v-model="searchForm.prodKeyType"
              @change="onProdKeyTypeChange"
            >
              <el-option
                v-for="node in prodKeyArr"
                :key="node.key"
                :label="node.label"
                :value="node.key"
              />
            </el-select>
            <el-input
              v-model="searchForm.prodKey"
              type="text"
              clearable
              :placeholder="prodKeyArr[searchForm.prodKeyType - 1].inputTips"
            />
          </el-form-item>
          <el-form-item
            prop="stockBillNo"
            :label="$t('stock.stockBillNo')+':'"
          >
            <el-input
              v-model="searchForm.stockBillNo"

              type="text"
              clearable
              :placeholder="$t('stock.pleaseStockBillNo')"
            />
          </el-form-item>
          <el-form-item
            prop="sourceOrderNo"
            :label="$t('stock.sourceOrderNo')+':'"
          >
            <el-input
              v-model="searchForm.sourceOrderNo"

              type="text"
              clearable
              :placeholder="$t('stock.pleaseSourceOrderNo')"
            />
          </el-form-item>
          <el-form-item
            prop="businessDetailTypeId"
            :label="$t('stock.stockBillType')+':'"
          >
            <el-select
              v-model="searchForm.stockBillType"

              clearable
              :placeholder="$t('tip.select')"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('takeStock.maker')+':'">
            <el-select
              v-model="searchForm.employeeId"
              clearable
            >
              <el-option
                v-for="node in employeeList"
                :key="node.employeeId"
                :label="node.mobile"
                :value="node.employeeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('stock.createOrderTime')+':'">
            <el-date-picker
              v-model="createDateRange"

              clearable
              type="datetimerange"
              :range-separator="$t('time.tip')"
              value-format="YYYY-MM-DD HH:mm:ss"
              :start-placeholder="$t('time.start')"
              :end-placeholder="$t('time.end')"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"
              @change="onCreateTimeChange"
            />
            <div
              class="default-btn"
              style="margin-left: 20px;"
              :class="{ 'is-active': createTimeActive === 1 }"
              @click="onSetDateRange(1)"
            >
              {{
                $t("time.t")
              }}
            </div>
            <div
              class="default-btn"
              :class="{ 'is-active': createTimeActive === 2 }"
              @click="onSetDateRange(2)"
            >
              {{
                $t("time.y")
              }}
            </div>
            <div
              class="default-btn"
              :class="{ 'is-active': createTimeActive === 3 }"
              @click="onSetDateRange(3)"
            >
              {{
                $t("time.n")
              }}
            </div>
            <div
              class="default-btn"
              :class="{ 'is-active': createTimeActive === 4 }"
              @click="onSetDateRange(4)"
            >
              {{
                $t("temp.m")
              }}
            </div>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="onResetForm('searchForm')"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('multishop:stockFlow:export')"
          class="default-btn"
          @click="onGetExportExcel()"
        >
          {{ $t('order.ExportingFiles') }}
        </div>
      </div>
      <div class="table-con">
        <el-table
          ref="dataListRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
          :row-key="(row, index) => { return row.stockBillLogItemId }"
          @selection-change="onSelectSome"
        >
          <el-table-column
            type="selection"
            align="center"
            fixed="left"
            width="55"
            :reserve-selection="true"
          />
          <el-table-column
            :label="$t('stock.stockBillNo')"
            prop="stockBillLogId"
            align="left"
            width="190"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.stockBillNo }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('stock.sourceOrderNo')"
            prop="sourceOrderNo"
            align="left"
            width="210"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.sourceOrderNo || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('stock.createOrderTime')"
            prop="createTime"
            align="left"
            width="160"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('stock.stockBillType')"
            prop="stockBillType"
            align="left"
            width="120"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ type(scope.row.stockBillType ) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('product.prodInfo')"
            prop="prodName"
            align="left"
            width="300"
          >
            <template #default="scope">
              <el-tooltip
                class="table-cell-text"
                placement="top"
                effect="light"
              >
                <template #content>
                  <div>
                    {{ scope.row.prodName }}<br>{{ scope.row.skuName }}
                  </div>
                </template>
                <span>
                  {{ scope.row.prodName }}
                  <span v-if="scope.row.skuName">{{ scope.row.skuName }}</span>
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('product.commodityCode')"
            prop="partyCode"
            width="200"
          >
            <template #default="scope">
              <div class="table-cell-text">
                {{ scope.row.partyCode }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('stock.outInStock')"
            prop="totalCount"
            align="left"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.stockType === 1 ? '-' : '+' }}{{ scope.row.stockCount }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('stock.unit')">
            <template #default>
              <span class="table-cell-text line-clamp-one">{{ $t('stock.pieces') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('takeStock.maker')"
            prop="employeeMobile"
            align="left"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.employeeMobile || '-' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>
    <!-- 导出 -->
    <el-dialog
      v-model="exportStockFlowVisible"
      :title="$t('stock.export')"
    >
      <el-radio
        v-model="exportRadio"
        :label="1"
      >
        {{ $t('stock.exportOfSearchFlow') }}
      </el-radio>
      <el-radio
        v-model="exportRadio"
        :label="2"
      >
        {{ $t('stock.exportOfSelectFlow') }}
      </el-radio>
      <template #footer>
        <span

          class="dialog-footer"
        >
          <div
            class="default-btn"
            @click="exportStockFlowVisible = false"
          >{{ $t('crud.filter.cancelBtn') }}</div>
          <div
            class="default-btn primary-btn"
            type="primary"
            @click="onConfirmExport"
          >{{ $t('crud.filter.submitBtn') }}</div>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import moment from 'moment'
import { ElMessage, ElLoading } from 'element-plus'
import { isAuth } from '@/utils'
const type = (val) => {
  switch (val) {
    case 1:return $t('stock.purchaseInStock')
    case 2:return $t('stock.returnToStorage')
    case 3:return $t('stock.otherEntries')
    case 4:return $t('stock.sellOut')
    case 5:return $t('stock.editOutBound')
    case 6:return $t('stock.otherOutbound')
    case 7:return $t('stock.inventoryInitialization')
    case 8:return $t('stock.orderCancelled')
    case 9:return $t('stock.editStorage')
    case 10:return $t('stock.profitStorage')
    case 11:return $t('stock.lossOutBound')
  }
}

let tempSearchForm = null // 保存上次点击查询的请求条件

const createTimeActive = ref(0)
const dataList = ref([])
const employeeList = ref([]) // 员工列表
const exportStockFlowVisible = ref(false) // 导出弹窗是否可见
const exportRadio = ref(1) //  1 按搜索条件导出 2 按选择项导出
let dataListSelections = [] // 已选择的数据项
const prodKeyArr = [
  { key: 1, label: $t('product.prodName'), inputTips: $t('takeStock.inputName') },
  { key: 2, label: $t('product.commodityCode'), inputTips: $t('takeStock.inputPartyCode') }
] // 商品筛选类型
const options = [
  { value: 0, label: $t('stock.all') },
  { value: 1, label: $t('stock.purchaseInStock') },
  { value: 2, label: $t('stock.returnToStorage') },
  { value: 3, label: $t('stock.otherEntries') },
  { value: 4, label: $t('stock.sellOut') },
  { value: 5, label: $t('stock.editOutBound') },
  { value: 6, label: $t('stock.otherOutbound') },
  { value: 7, label: $t('stock.inventoryInitialization') },
  { value: 8, label: $t('stock.orderCancelled') },
  { value: 9, label: $t('stock.editStorage') },
  { value: 10, label: $t('stock.profitStorage') },
  { value: 11, label: $t('stock.lossOutBound') }
] // 单据类型
const createDateRange = ref([]) // 制单时间范围
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({
  prodKeyType: 1, // 1：商品名称 2：商品编码
  sourceOrderNo: '', // 关联单号
  prodKey: '', // 搜索商品关键词
  stockBillNo: '', // 单据编号
  stockBillType: 0, // 单据类型
  employeeId: '', // 制单员工id
  createStartTime: '', // 制单起始时间
  createEndTime: '', // 制单结束时间
  stockBillItemType: 1
}) // 搜索
onMounted(() => {
  getDataList(page)
  // 获取员工列表
  getEmployeeList()
})

const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    page.currentPage = 1
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  http({
    url: http.adornUrl('/shop/stockBillLogItem/flow'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
  }).catch(() => {
  })
}
const getEmployeeList = () => {
  http({
    url: http.adornUrl('/sys/shopEmployee/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    employeeList.value = data
  })
}
const onGetExportExcel = () => {
  exportStockFlowVisible.value = true
}

const onSearch = (newData = false) => {
  getDataList(page, newData)
}
const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList(page)
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList(page)
}
const searchFormRef = ref(null)
const onResetForm = () => {
  searchFormRef.value.resetFields()
  searchForm.employeeId = ''
  searchForm.prodKeyType = 1
  searchForm.prodKey = ''
  searchForm.createStartTime = ''
  searchForm.createEndTime = ''
  searchForm.sourceOrderNo = null
  searchForm.stockBillType = 0
  searchForm.stockBillNo = null
  createDateRange.value = []
  createTimeActive.value = 0
}
const onProdKeyTypeChange = () => {
  searchForm.prodKey = ''
}
const onCreateTimeChange = () => {
  if (!createDateRange.value || createDateRange.value.length === 0) {
    searchForm.createStartTime = null
    searchForm.createEndTime = null
  } else {
    searchForm.createStartTime = createDateRange.value[0]
    searchForm.createEndTime = createDateRange.value[1]
  }
}
/**
 * 确定导出
 */
let isSubmit
const onConfirmExport = () => {
  if (exportRadio.value !== 1 && exportRadio.value !== 2) {
    ElMessage({
      message: $t('stock.exportRadioEmptyTips'),
      type: 'error',
      duration: 1500,
      onClose: () => {
        isSubmit = false
      }
    })
    return
  }
  if (isSubmit) {
    return
  }
  isSubmit = true
  // 准备参数
  let params = {}
  if (exportRadio.value === 1) {
    // 导出模式为按搜索条件导出
    if (page.total === 0) {
      ElMessage({
        message: $t('stock.exportStockLogSearchEmptyTips'),
        type: 'error',
        duration: 1500,
        onClose: () => {
          isSubmit = false
        }
      })
      return
    }
    params = searchForm
    params.stockBillLogItemIds = null
  } else {
    // 导出模式为按选中的数据导出
    if (dataListSelections.length === 0) {
      ElMessage({
        message: $t('stock.exportStockLogSelectEmptyTips'),
        type: 'error',
        duration: 1500,
        onClose: () => {
          isSubmit = false
        }
      })
      return
    }
    params.stockBillLogItemIds = dataListSelections.map(item => {
      return item.stockBillLogItemId
    })
  }
  const loading = ElLoading.service({
    lock: true,
    target: '.mod-stock-flow',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('formData.exportIng')
  })
  http({
    url: http.adornUrl('/shop/stockBillLogItem/exportFlow'),
    method: 'get',
    params: http.adornParams(params),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('stock.stockFlowXls')
    const elink = document.createElement('a')
    if ('download' in elink) {
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      navigator.msSaveBlob(blob, fileName)
    }
    ElMessage({
      message: $t('stock.exportSuccess'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        isSubmit = false
        exportStockFlowVisible.value = false
      }
    })
  }).catch((e) => {
    loading.close()
    isSubmit = false
  })
}
// 多选变化
const onSelectSome = (val) => {
  dataListSelections = val
}
/**
 * 根据选项设置时间
 * 1:今天 2:昨天 3: 近七天 4:近30天 5:近60天
 */
const onSetDateRange = (val) => {
  let startDay = null
  let endDay = null
  if (val === 1) {
    startDay = 0
    endDay = 0
  } else if (val === 2) {
    startDay = -1
    endDay = -1
  } else if (val === 3) {
    startDay = -7
    endDay = -1
  } else if (val === 4) {
    startDay = -30
    endDay = -1
  } else {
    return
  }
  // 开始时间
  const startTime = moment()
    .add(startDay, 'days')
    .startOf('days')
    .format('LL')
  // 结束时间
  const endTime = moment().add(endDay, 'days').endOf('days').format('LL')
  createDateRange.value = [startTime, endTime]
  searchForm.createStartTime = startTime
  searchForm.createEndTime = endTime
  createTimeActive.value = val
}

</script>

<style lang="scss" scoped>
.mod-stock-flow.component-sku-stock-flow {
  .search-bar {
    .search-form {
      .is-active {
        color: #155BD4;
      }
    }
  }
}
</style>
